package com.ksj.controller;

import com.ksj.util.IdCardRecognition;
import com.ksj.util.IdCheck2Util;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/api/ocr")
public class OcrController {

    @PostMapping("/idcard")
    public HashMap<String, Object> handleIdCardUpload(@RequestParam("file") MultipartFile file) {
        HashMap<String, Object> response = new HashMap<>();

        try {
            // 1. 验证文件
            if (file.isEmpty()) {
                response.put("status", "error");
                response.put("message", "文件不能为空");
                return response;
            }

            // 2. 转换为InputStream
            ByteArrayInputStream inputStream = new ByteArrayInputStream(file.getBytes());

            // 3. 调用OCR识别
            HashMap<String, String> ocrResult = IdCardRecognition.recognizeIdCard(inputStream);

            // 4. 处理响应
            if (ocrResult != null && !ocrResult.containsKey("error")) {
                response.put("status", "success");
                response.putAll(ocrResult);
            } else {
                response.put("status", "error");
                response.put("message", ocrResult != null ?
                        ocrResult.get("error") : "识别服务无返回");
            }

        } catch (IOException e) {
            response.put("status", "error");
            response.put("message", "文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "OCR服务异常: " + e.getClass().getSimpleName());
        }

        IdCheck2Util idCheck2Util = new IdCheck2Util();
        String idcheck = idCheck2Util.idcheck((String) response.get("name"), (String) response.get("idNumber"));
        if (idcheck.equals("身份认证成功")){
            return response;
        }
        return null;
    }
}